package com.tn.handler;

import com.gitee.hifong45.FE;
import com.gitee.hifong45.Ret;
import com.gitee.hifong45.Str;
import com.tn.controller.alarm.common.model.CommonVO;
import com.tn.exception.CommonException;
import com.tn.exception.DatabaseOperationFailedException;
import com.tn.exception.InvalidParamException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @program: tn_aucy_java
 * @description:
 * @author: yangjiayao
 * @create: 2021-11-12 15:20
 */
@Slf4j
@ControllerAdvice
public class CommonExceptionHandler {
    /**
     * 通用异常
     *
     * @param e 异常
     * @return 响应
     */
    @ExceptionHandler(CommonException.class)
    @ResponseBody
    public CommonVO<Object> handleCommonException(CommonException e) {
        log.error("Handle common exception!");
        CommonVO<Object> response = new CommonVO<>();
        response.setCode(e.getCode());
        response.setMsg(e.getMessage());
        return response;
    }

    /**
     * 数据库处理异常
     *
     * @param e 异常
     * @return 响应
     */
    @ExceptionHandler(DatabaseOperationFailedException.class)
    @ResponseBody
    public CommonVO<Object> handleDatabaseOperationFailedException(DatabaseOperationFailedException e) {
        log.error("Handle database operation failed exception!");
        CommonVO<Object> response = new CommonVO<>();
        response.setCode(e.getCode());
        response.setMsg(e.getMessage());
        return response;
    }

    /**
     * 用户参数异常
     *
     * @param e 异常
     * @return 响应
     */
    @ExceptionHandler(InvalidParamException.class)
    @ResponseBody
    public CommonVO<Object> handleInvalidParamException(InvalidParamException e) {
        log.error("Handle Invalid param exception!");
        CommonVO<Object> response = new CommonVO<>();
        response.setCode(e.getCode());
        response.setMsg(e.getMessage());
        return response;
    }

    /**
     * 快速异常
     * @param e 异常
     * @return 响应
     */
    @ExceptionHandler(FE.class)
    @ResponseBody
    public Ret<Object> handleFEException(FE e) {
        Ret<Object> ret = Ret.Fail(e.code, e.msg + Str.orElse(e.extMsg, ""));
        log.error(ret.toJsonStr());
        return ret;
    }
}
